package com.eastedu.superise.handler.question;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastedu.repository.ktree.mapper.KnowledgeNodeMapper;
import com.eastedu.repository.question.mapper.QuestionAssociationMapper;
import com.eastedu.repository.question.mapper.QuestionBasicInfoMapper;
import com.eastedu.repository.question.po.QuestionAssociationPO;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 袁松明
 */
@Slf4j
@Service
@DS("question")
public class QuestionDeleteKnowledgeHistoricalDataHandler extends AbstractHistoricalDataHandler<QuestionBasicInfoPO> {
    private final QuestionAssociationMapper questionAssociationMapper;
    private final QuestionBasicInfoMapper questionBasicInfoMapper;
    private final KnowledgeNodeMapper knowledgeNodeMapper;

    public QuestionDeleteKnowledgeHistoricalDataHandler(QuestionAssociationMapper questionAssociationMapper,
                                                        QuestionBasicInfoMapper questionBasicInfoMapper,
                                                        KnowledgeNodeMapper knowledgeNodeMapper) {
        this.questionAssociationMapper = questionAssociationMapper;
        this.questionBasicInfoMapper = questionBasicInfoMapper;
        this.knowledgeNodeMapper = knowledgeNodeMapper;
    }

    @Override
    protected String getSql() {
        /*
            故事ID：89095
            初中数学、生物、
            高中数学、化学、生物

            'CZ'    'SX','SW'
            'GZ'    'SX','SW','HX'
         */
        return "SELECT " +
                "   DISTINCT question.* " +
                "FROM" +
                "   question_service.t_question_basic_info AS question " +
                "   INNER JOIN question_service.t_question_association AS question_knowledge ON question.id = question_knowledge.question_id AND question_knowledge.type = 1 " +
                "WHERE " +
                "   question.study_period IN ( 'CZ') " +
                "   AND question.`subject` IN ( 'SX','SW' ) " +
                "ORDER BY question.id";
    }

    @Override
    public void callback(QuestionBasicInfoPO questionBasicInfoPo) throws SQLException {
        log.debug("试题ID：{}", questionBasicInfoPo.getId());
        List<QuestionAssociationPO> knowledgePoints =
                questionAssociationMapper.findAllByQuestionId(questionBasicInfoPo.getId());
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            log.info("试题ID：{} 无知识点", questionBasicInfoPo.getId());
            return;
        }
        List<String> parentNodeGuids = this.listParentNodeGuids(knowledgePoints);
        if (CollectionUtils.isEmpty(parentNodeGuids)) {
            log.info("试题ID：{} 无非末级知识点", questionBasicInfoPo.getId());
            return;
        }
        List<QuestionAssociationPO> remainKnowledgePoints = this.deleteParentNodes(knowledgePoints, parentNodeGuids);
        // 关联表type=1，主表上type=0
        remainKnowledgePoints.forEach(item -> {
            item.setType(0);
        });
        String knowledgeString = JSON.toJSONString(remainKnowledgePoints);
        questionBasicInfoMapper.updateKnowledgeById(questionBasicInfoPo.getId(), knowledgeString);
        log.info("删除试题非末级知识点成功，试题ID：{}", questionBasicInfoPo.getId());
    }

    private List<String> listParentNodeGuids(List<QuestionAssociationPO> knowledgePoints) {
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            return new ArrayList<>();
        }
        List<String> knowledgeNodeGuids = knowledgePoints.stream().filter(Objects::nonNull)
                .map(QuestionAssociationPO::getAssociationId).filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(knowledgeNodeGuids)) {
            return new ArrayList<>();
        }
        return knowledgeNodeMapper.findParentGuidByGuidIn(knowledgeNodeGuids);
    }

    private List<QuestionAssociationPO> deleteParentNodes(List<QuestionAssociationPO> knowledgePoints,
                                                          List<String> parentNodeGuids) {
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            return new ArrayList<>();
        }
        if (CollectionUtils.isEmpty(parentNodeGuids)) {
            return knowledgePoints;
        }
        Iterator<QuestionAssociationPO> iterator = knowledgePoints.iterator();
        while (iterator.hasNext()) {
            QuestionAssociationPO questionAssociationPo = iterator.next();
            if (Objects.nonNull(questionAssociationPo)
                    && Objects.nonNull(questionAssociationPo.getAssociationId())
                    && parentNodeGuids.contains(questionAssociationPo.getAssociationId())) {
                questionAssociationMapper.deleteById(questionAssociationPo.getId());
                iterator.remove();
            }
        }
        return knowledgePoints;
    }
}
